/*
 * CRecordStore.cpp
 *
 *  Created on: 2018年5月17日
 *      Author: zhengboyuan
 */

#include "CRecordStore.h"
#include "CDataStore.h"
#include "Path.h"
#include "CLog.h"


namespace av
{



CRecordStore::CRecordStore():
        m_dataStore(new CDataStore())
{
}

CRecordStore::~CRecordStore()
{
    close();
}

bool CRecordStore::open(const char* dbpath)
{
    if (dbpath == NULL)
    {
        return false;
    }

    m_dbpath = dbpath;

    if (!m_dataStore->open(m_dbpath))
    {
        return false;
    }

    return true;
}

void CRecordStore::close()
{
    m_dataStore->close();
}

bool CRecordStore::isOpen()
{
    return m_dataStore->isOpen();
}

int CRecordStore::findRecord(const MRecordQuery& query, int offset, MRecord* records, int size)
{
    return m_dataStore->searchRecord(query, offset, records, size);
}

int CRecordStore::countRecord(const MRecordQuery& query)
{
	return m_dataStore->countRecord(query);
}

bool CRecordStore::getRecord(int id, av::MRecord& record)
{
	return m_dataStore->getRecord(id, record);
}

bool CRecordStore::deleteRecord(int id)
{
    av::MRecord record;
    memset(&record, 0, sizeof(record));
    if (!m_dataStore->getRecord(id, record))
    {
        CLog::warning("can not find record by id %d\n", id);
        return false;
    }

    deleteRecord(record);

    return true;
}

bool CRecordStore::deleteRecordWithFileName(const char* filename)
{
    if (!filename)
    {
        return false;
    }

    av::MRecord record;
    memset(&record, 0, sizeof(record));
    if (!m_dataStore->findRecord(filename, record))
    {
        return false;
    }

    deleteRecord(record);
    return true;
}

bool CRecordStore::findRecordWithFileName(const char* filename, MRecord* record)
{
    if (!filename || !record)
    {
        return false;
    }

    return m_dataStore->findRecord(filename, *record);
}

void CRecordStore::clearBrokenRecord(const char* chl)
{
    if (m_clearThread)
    {
        m_clearThread->stop();
        m_clearThread.reset();
    }

    m_clearThread.reset(new RecordClearThread(m_dataStore, chl, this));
    m_clearThread->start();
}

void CRecordStore::deleteRecord(av::MRecord& record)
{
    m_dataStore->removeRecord(record.id);

    if (!comn::Path::deleteFile(record.filepath))
    {
        CLog::warning("failed to delete file %s\n", record.filepath);
    }

    //std::string eventFile = StorageChannel::getEventFilePath(record.filepath, strlen(record.filepath));
    //comn::Path::deleteFile(eventFile);
}

void CRecordStore::onRecordCleared(const std::string& chl, int cleared)
{
    // pass
}


}
